import java.util.LinkedList;
import java.util.List;

public class LeetCode841 {
    public static void main(String[] args) {
        int[][] arr = new int[][]{{1},{2},{3},{}};
        int[][] arr2 = new int[][]{{1,3},{3,0,1},{2},{0}};

        int[][] roomArr = arr2;
        List<List<Integer>> rooms = new LinkedList<>();
        for (int i = 0; i< roomArr.length; i++){
            List<Integer> room = new LinkedList<>();
            int[] roomKeysArr =  roomArr[i];
            for (int j = 0; j <roomKeysArr.length; j++){
                room.add(roomKeysArr[j]);
            }
            rooms.add(room);
        }

        System.out.println(canVisitAllRooms(rooms));
    }

    public static boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean result = false;
        if (rooms.size() > 0){
            boolean[] openList = new boolean[rooms.size()];
            openList[0] = true;
            List<Integer> keyList = rooms.get(0);

            while (!keyList.isEmpty()){
                List<Integer>  newKeyList = new LinkedList<>();
                for (int key:keyList){
                    openList[key] = true;
//                    newKeyList.addAll(rooms.get(key));
                    for (int kk : rooms.get(key)){
                        if (!openList[kk]){
                            newKeyList.add(kk);
                        }
                    }
                }

                keyList = newKeyList;
            }


            for (boolean opened: openList){
                if (!opened){
                    return false;
                }
            }
            return true;
        }

        return result;
    }
}
